package com.galeno.movie;

import com.alibaba.fastjson.JSON;
import com.galeno.json.MovieBean;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/7/2611:25
 */
public class MovieAvg {
    static class MovieAvgMap extends Mapper<LongWritable, Text, IntWritable, MovieBean> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            try {

                    String line = value.toString();
                    MovieBean movieBean = JSON.parseObject(line, MovieBean.class);
                    // System.out.println(movieBean);
                    int movie = movieBean.getMovie();
                    IntWritable kout = new IntWritable(movie);
                    context.write(kout,movieBean);



            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class MovieAvgRed extends Reducer<IntWritable,MovieBean,IntWritable, DoubleWritable>{
        @Override
        protected void reduce(IntWritable key, Iterable<MovieBean> values, Context context) throws IOException, InterruptedException {
            int count=0;
            double sum=0;
            for (MovieBean value : values) {
                double rate = value.getRate();
                sum=sum+rate;
                count++;
            }
            double avgRate=(sum/count);
            System.out.println(avgRate);
            DoubleWritable vout = new DoubleWritable(avgRate);
            context.write(key,vout);
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf=new Configuration();
        conf.set("fs.defaultFS","file:/");
        Job job=Job.getInstance(conf,"MovieAvg");
        job.setMapperClass(MovieAvgMap.class);
        job.setReducerClass(MovieAvgRed.class);
        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(MovieBean.class);
        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(DoubleWritable.class);
        FileInputFormat.setInputPaths(job,new Path("D:/mrdata/movie/input"));
        FileOutputFormat.setOutputPath(job,new Path("D:/mrdata/movie/output"));

        job.waitForCompletion(true);




    }


}
